package com.rich.dmr.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.DmrApplication;
import com.rich.dmr.R;
import com.rich.dmr.handler.DmrHandler;
import com.rich.dmr.model.Frequency;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.Constant;
import com.rich.dmr.utils.ConvertUtils;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.SoundPoolUtils;

import java.util.ArrayList;
import java.util.List;

import rich.dmr.DmrManager;

public class FrequencyActivity extends BaseActivity implements View.OnClickListener, DmrHandler.HandlerCallBack {
    private String TAG = "rich---FrequencyActivity";
    private DmrManager dmrManager;
    private List<Frequency> frequencyList = new ArrayList<>();
    private FrequencyGridAdapter adapter;
    private RecyclerView recyclerView;
    private int mDevHitCountdown;
    private Toast mDevHitToast;
    private static final int TAPS_TO_BE_A_DEVELOPER = 10;
    private DataBaseUtils mDataBaseUtils;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frequency);
        SimpleToolbar simpleToolbar = findViewById(R.id.frequency_tools_bar);
        simpleToolbar.seMiddleTitleClickListener(this);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setMainTitle(getString(R.string.tools_frequency));

        dmrManager = (DmrManager) getSystemService("dmrservice");
        mDataBaseUtils = DataBaseUtils.getInstance(this);
        frequencyList = mDataBaseUtils.findFrequencyList();

        DmrHandler.getInstance().setHandlerCallBack(this);
        recyclerView = findViewById(R.id.all_frequency);
        recyclerView.setLayoutManager(new FrequencyGridLayoutManager(
                2, StaggeredGridLayoutManager.VERTICAL));
        adapter = new FrequencyGridAdapter(this);
        recyclerView.setAdapter(adapter);

        mDevHitCountdown = TAPS_TO_BE_A_DEVELOPER;
        mDevHitToast = null;
        DmrApplication.getInstance().addActivity(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.txt_left_title:
                finish();
                break;
            case R.id.txt_main_title:
                activeSysWriterFrequency();
                break;
            default:
                break;
        }
    }

    @Override
    public void updateFrequency(Message msg) {
        if (msg.what == Constant.MSG_CHANNEL_OBJ) {
            frequencyList = mDataBaseUtils.findFrequencyList();
            adapter.notifyDataSetChanged();
            recyclerView.smoothScrollToPosition(frequencyList.size() - 1);
        }
    }

    class FrequencyGridAdapter extends RecyclerView.Adapter<FrequencyGridAdapter.LinearViewHolder> {
        private String TAG = "rich---FrequencyGridAdapter";
        private Context mContext;

        FrequencyGridAdapter(Context mContext) {
            this.mContext = mContext;
        }

        @NonNull
        @Override
        public FrequencyGridAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            return new FrequencyGridAdapter.LinearViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_rv_frequency_list, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final FrequencyGridAdapter.LinearViewHolder holder, final int position) {
            Frequency frequency = frequencyList.get(position);
            holder.rxFrequency.setText("Tx:" + ConvertUtils.div(frequency.getRxFrequency(), 1000000));
            holder.txFrequency.setText("Rx:" + ConvertUtils.div(frequency.getTxFrequency(), 1000000));

            if (dmrManager.getReceiveFrequency() == frequency.getRxFrequency() && dmrManager.getTransmitFrequency() == frequency.getTxFrequency()) {
                holder.frequencyOnline.setBackgroundResource(R.drawable.shape_online);
            } else {
                holder.frequencyOnline.setBackgroundResource(R.drawable.shape_setting_offline);
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isWrite = false;
                    frequencyList = mDataBaseUtils.findFrequencyList();
                    Frequency frequency = frequencyList.get(position);
                    if (frequencyList.size() > 0) {
                        if (frequency.getRxFrequency() != dmrManager.getReceiveFrequency()) {
                            dmrManager.setReceiveFrequency(frequency.getRxFrequency());
                            isWrite = true;
                        }

                        if (frequency.getTxFrequency() != dmrManager.getTransmitFrequency()) {
                            dmrManager.setTransmitFrequency(frequency.getTxFrequency());
                            isWrite = true;
                        }

                        if (isWrite) {
                            SoundPoolUtils.getInstance(FrequencyActivity.this).playSound(false);
                            notifyDataSetChanged();
                            dmrManager.flush();
                        }
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return frequencyList.size();
        }

        class LinearViewHolder extends RecyclerView.ViewHolder {
            private TextView txFrequency;
            private TextView rxFrequency;
            private TextView frequencyOnline;


            private LinearViewHolder(View itemView) {
                super(itemView);
                txFrequency = itemView.findViewById(R.id.tx_frequency);
                rxFrequency = itemView.findViewById(R.id.rx_frequency);
                frequencyOnline = itemView.findViewById(R.id.frequency_show_online);
            }
        }
    }

    static class FrequencyGridLayoutManager extends StaggeredGridLayoutManager {

        FrequencyGridLayoutManager(int spanCount, int orientation) {
            super(spanCount, orientation);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DmrHandler.getInstance().removeHandlerCallBack(this);
    }

    public void activeSysWriterFrequency() {
        Log.d(TAG, "mDevHitCountdown=" + mDevHitCountdown);
        if (mDevHitCountdown > 0) {
            mDevHitCountdown--;
            if (mDevHitCountdown == 0) {
                mDevHitCountdown++;
                mDevHitCountdown = 0;
                if (mDevHitToast != null) {
                    mDevHitToast.cancel();
                }
                mDevHitToast = Toast.makeText(this, "write number mode open.",
                        Toast.LENGTH_LONG);
                mDevHitToast.show();
                dmrManager.openOrCloseAdb(true);
                dmrManager.skipAdbConfirm(true);
            } else if (mDevHitCountdown > 0
                    && mDevHitCountdown < (TAPS_TO_BE_A_DEVELOPER - 2)) {
                if (mDevHitToast != null) {
                    mDevHitToast.cancel();
                }
            }

        } else {
            if (mDevHitToast != null) {
                mDevHitToast.cancel();
            }
        }
    }
}
